﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Resources;
using Cesave.Domain.Core;
using System.Data;
using Cesave.Domain.PermisosModule.Entities;

namespace Cesave.Domain.PermisosModule.Contracts.Areas
{
	public class AreaService
		: IAreaService
	{

		private IAreaRepository _areaRepository;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="areaRepository"></param>
		public AreaService(IAreaRepository areaRepository)
		{
			if (areaRepository == null)
				throw new ArgumentNullException(Messages.exception_DependenciesAreNotInitialized);
			_areaRepository = areaRepository;
		}

		#region IAreaService Members

		public void AddArea(Entities.Area area)
		{

			IUnitOfWork unitOfWork = _areaRepository.StoreContext;
			_areaRepository.Add(area);
			try
			{
				unitOfWork.Commit();
			}
			catch (OptimisticConcurrencyException)
			{
				unitOfWork.RollbackChanges();
				unitOfWork.CommitAndRefreshChanges();
			}
		}

		public void ChangeArea(Entities.Area area)
		{
			if (area == null)
				throw new ArgumentNullException(Messages.exception_InvalidArgument);
			IUnitOfWork unitOfWork = _areaRepository.StoreContext;
			_areaRepository.Modify(area);
			try
			{
				unitOfWork.Commit();
			}
			catch (OptimisticConcurrencyException)
			{
				unitOfWork.RollbackChanges();
				unitOfWork.CommitAndRefreshChanges();
			}
		}

		public List<Area> FindAreasByJunta(Guid juntaGuid)
		{
			if (juntaGuid == Guid.Empty)
				throw new ArgumentException(Messages.exception_InvalidArgument);
			AreasByJuntaSpecification specification = new AreasByJuntaSpecification(juntaGuid);
			return _areaRepository.FindAreasByJunta(specification).ToList();
		}

		public void DeleteArea(Area area)
		{
			if (area == null)
				throw new ArgumentNullException(Messages.exception_InvalidArgument, "area");
			IUnitOfWork unitOfWork = _areaRepository.StoreContext;
			_areaRepository.Remove(area);
			try
			{
				unitOfWork.Commit();
			}
			catch (OptimisticConcurrencyException)
			{
				unitOfWork.RollbackChanges();
				unitOfWork.CommitAndRefreshChanges();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="specification"></param>
		/// <returns></returns>
		public Area FindAreaByGuid(Guid areaGuid)
		{
			if (areaGuid == Guid.Empty)
				throw new ArgumentException(Messages.exception_InvalidArgument, "specification");
			AreaByGuidSpecification specification = new AreaByGuidSpecification(areaGuid);
			return _areaRepository.GetBySpec(specification).FirstOrDefault();
		}

		#endregion

		#region IDisposable Members

		public void Dispose()
		{
			if (_areaRepository != null && _areaRepository.StoreContext != null)
				_areaRepository.StoreContext.Dispose();
		}

		#endregion
	}
}
